<template>
  <nut-config-provider :theme="theme" :theme-vars="themeVars">
    <view :style="{backgroundColor: themeVars.pageBackgroundColor,padding: themeVars.pagePadding,height:'100vh'}">
      <!--顶部-->
      <view>

        <nut-searchbar v-model="queryParam.searchKey" @clear="search">
          <template #leftout>
            <view style="display: flex;align-items: center" @click="visible=true">
              <view class="city-box">{{ queryParam.adcodeName }}</view>
              <IconFont name="rect-right" size="14"></IconFont>
            </view>
          </template>
          <template #leftin>
            <Search2/>
          </template>
          <template #rightout><span @click="search">搜索</span></template>
        </nut-searchbar>
         <view
            style="font-size: 13px;background: white;border-radius: 10px;margin-top: 5px;padding: 6px;display: flex;justify-content: space-between"
            @click="catVisible=true">
          <view style="color: grey">选择分类</view>
          <view style="color:red">
            {{ queryParam.productCategoryName }}
          </view>
        </view>
      </view>
      <!-- 列表-->
      <view v-if="data.length >0">
        <Shop  class="card"  @click="Taro.navigateTo({url:'/pages/view/enterpriseIntro/index?id='+item.id})" :data="item" v-for="item in data"
              style="margin-bottom: 5px; background: white"/>
      </view>

      <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>


    </view>
    <nut-cascader
        v-model:visible="visible"
        v-model="queryParam.adcode"
        title="选择地址"
        :options="areaData"
        @change="change"


    ></nut-cascader>
    <nut-cascader
        v-model:visible="catVisible"
        v-model="queryParam.productCategoryArr"
        text-key="name"
        value-key="id"
        children-key="items"
        title="选择分类"
        :options="busiTypeList"
        @change="catChange"
    ></nut-cascader>
  </nut-config-provider>
</template>

<script>
import {ref} from 'vue';
import {IconFont} from '@nutui/icons-vue'
import useTheme from "../../../hooks/useTheme";
import Taro from "@tarojs/taro";
import {amapCGeocodeRegeo} from "../../../api/dev";
import {parseAddressCode} from "../../../utils/strUtils";
import Shop from "../../../components/shop/index.vue";
import {twEnterprisePageApi} from "../../../api/enterprise";
import {twProductCategoryPage} from "../../../api/productCategory";
import {emptyUrl} from "../../../utils/imgUtils";


const areaData = JSON.parse(Taro.getStorageSync("areaJson"));
const {theme, themeVars} = useTheme()

const visible = ref(false)
const catVisible = ref(false)




const change = (val, arr) => {
  console.log('change', val, arr)
  queryParam.value.adcode = val;
  queryParam.value.adcodeName = arr[2].text;
  queryParam.value.addrAdcode = val[2]
  refresh()

}

const catChange = (val, arr) => {
  console.log('change', val,"arr", arr)
  queryParam.value.productCategoryArr = val;
  queryParam.value.productCategoryName = arr[0].text;
  queryParam.value.productCategoryId =  val[0]
  refresh()
}

const queryParam = ref({
  searchKey: "",
  current: 1,
  size: 10,
  pages: 0,
  addrAdcode: '',
  productCategoryArr:[],
  productCategoryId: '',
  productCategoryName: '',
})


const data = ref([]);

const getData = () => {
  twEnterprisePageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend",status:'ENABLE'}).then(res => {

    if (200 == res.code) {
      data.value = [...data.value, ...res.data.records]
      queryParam.value.pages = res.data.pages;
      console.log("queryParam", queryParam.value)
      console.log("res.data", res.data)
    }
  }).finally(() => {
    Taro.stopPullDownRefresh();
    loadMoreLoading.value = false

  })
}


const refresh = () => {
  queryParam.value.current = 1;
  queryParam.value.size = 10;
  data.value = []
  getData()
}

const loadMoreLoading = ref(false);
const loadMore = () => {
  if (queryParam.value.current >= queryParam.value.pages) {
    console.log("没有更多数据了")
    Taro.showToast({title: "没有更多数据了", icon: 'none', duration: 1500,});
    return
  }
  loadMoreLoading.value = true
  queryParam.value.current = queryParam.value.current + 1
  getData()
}


const getLocation = () => {
  Taro.getLocation({
    type: 'gcj02',
    altitude: true,
    isHighAccuracy: true,
    success: function (res) {
      const {
        address,
        errMsg,
        latitude,
        longitude,
        name
      } = res
      amapCGeocodeRegeo(`${longitude},${latitude}`).then(res => {
        if (200 == res.code) {
          const data1 = res.data.addressComponent;
          queryParam.value.adcode = parseAddressCode(data1.adcode);
          queryParam.value.addrAdcode = parseAddressCode(data1.adcode)[2];
          queryParam.value.adcodeName = data1.district;
          console.log("queryParam.value.adcode", queryParam.value)
          refresh()
        }
      })
      console.log(latitude, longitude)
    },
    fail: function (rr) {
      console.error("getLocation fail", rr)
      Taro.getSetting({
        success: res => {
          if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
            // 用户拒绝了授权
            Taro.showModal({
              title: '提示',
              content: '您拒绝了定位权限，将无法选择地址，修改位置消息',
              success: res => {
                console.log("showModal ", res)
                if (res.confirm) {
                  // 跳转设置页面
                  Taro.openSetting({
                    success: res => {
                      if (res.authSetting['scope.userLocation']) {
                        // 授权成功，重新定位
                        Taro.getLocation({
                          success: res => {

                            console.log("位置信息 ", res)
                          }
                        });
                      } else {
                        // 没有允许定位权限
                        Taro.showToast({
                          title: '您拒绝了定位权限，将无法选择地址，修改位置消息',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
          }
        }
      })
    }
  })
}


const busiTypeList = ref([]);
const getProductCategoryPage = () => {
  twProductCategoryPage({current: 1, size: 1000, level: 1,status:'ENABLE'}).then(res => {
    busiTypeList.value =[{id:'',name:"所有分类"}, ...res.data.records]
    queryParam.value.productCategoryArr = [busiTypeList.value[0].id||""];
    queryParam.value.productCategoryId = busiTypeList.value[0].id;
    queryParam.value.productCategoryName = busiTypeList.value[0].name;
  })
}


const search = () => {
  refresh()
}

export default {
  methods: {
    emptyUrl() {
      return emptyUrl
    }
  },

  components: {Shop, IconFont},

  // 可以使用所有的 Vue 生命周期方法
  mounted() {
  },

  onLoad() {
    getLocation();
    getProductCategoryPage()

  },

  onReady() {
  },

  onShow() {

  },

  onHide() {
  },

  onPullDownRefresh() {
    console.log("onPullDownRefresh")
    refresh()
  },
  onReachBottom() {
    console.log("onReachBottom")
    loadMore()
  },


  setup() {


    return {
      theme,
      themeVars,
      Taro,
      areaData,


      queryParam,
      search,
      visible,
      change,
      catVisible,
       catChange,
      data,
      busiTypeList

    }
  }

}


</script>

<style>

.city-box {
  font-size: 28px;
  width: 110px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>